package br.com.cultbook.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import java.lang.reflect.ParameterizedType;

public abstract class CultBookDAO <T>{	
	protected Class<T> classe;

    @SuppressWarnings("unchecked")
	public CultBookDAO() {
        try {
            this.classe = 
            	(Class<T>)
            	((ParameterizedType) 
            			getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        }
        catch (Exception e) {
            
        }
    }
	public void incluir(EntityManager em, T t) {
		em.persist(t);
	}

	public void alterar(EntityManager em, T t) {
		em.merge(t);
	}

	public void excluir(EntityManager em, T t) {
		em.remove(t);
	}

	public Object buscarPorId(EntityManager em, long id) {		
		return em.find(this.classe, id);
	}

	@SuppressWarnings("unchecked")
	public List<T> pesquisar(EntityManager em, String key) {		
		final String ejbql = "select obj from " + classe.getSimpleName() + " obj where obj.nome like ? ";
		String parametro = "%%";

        if (key != null) {
        	parametro = "%" + key + "%";
        }
        Query query = em.createQuery(ejbql);
        query.setParameter(1, parametro);
        
        List<T> list = (List<T>) query.getResultList();
		return list;
	}
	
	@SuppressWarnings("unchecked")
	public List<T> buscarTodos(EntityManager em) {
		System.out.println("passou");
		final String ejbql = "select obj from " + classe.getSimpleName() + " obj";
        List<T> list = (List<T>) em.createQuery(ejbql).getResultList();
		return list;
	}	
}
